package by.koleda.benicetobunnies.provider;

import java.util.ArrayList;

import by.koleda.benicetobunnies.provider.BunniesDatabase.Tables;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class BunniesProvider extends ContentProvider {

	private static final UriMatcher sUriMatcher = buildUriMatcher();

	private static final int COMPANIES = 100;
	private static final int COMPANIES_ID = 101;

	private static UriMatcher buildUriMatcher() {
		final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
		final String authority = BunniesContract.CONTENT_AUTHORITY;

		matcher.addURI(authority, "companies", COMPANIES);
		matcher.addURI(authority, "companies/*", COMPANIES_ID);
		return matcher;
	}

	private BunniesDatabase bunniesDatabase;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		final SQLiteDatabase db = bunniesDatabase.getWritableDatabase();
		int deleteCount = 0;
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case COMPANIES: {
			deleteCount = db.delete(Tables.COMPANIES, selection, selectionArgs);
			break;
		}
		case COMPANIES_ID: {
			String idStr = uri.getLastPathSegment();
			String where = BaseColumns._ID + " = " + idStr;
			if (!TextUtils.isEmpty(selection)) {
				where += " AND " + selection;
			}
			deleteCount = db.delete(Tables.COMPANIES, where, selectionArgs);
			break;
		}
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		if (deleteCount > 0) {
			getContext().getContentResolver().notifyChange(uri, null);
		}
		return deleteCount;
	}

	@Override
	public String getType(Uri uri) {
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case COMPANIES:
			return BunniesContract.Companies.CONTENT_TYPE;
		default:
			throw new UnsupportedOperationException("Unknown uri: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		final SQLiteDatabase db = bunniesDatabase.getWritableDatabase();
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case COMPANIES: {
			long id = db.insertOrThrow(Tables.COMPANIES, null, values);
			getContext().getContentResolver().notifyChange(uri, null);
			Uri insertionUri = ContentUris.withAppendedId(
					BunniesContract.Companies.CONTENT_URI, id);
			return insertionUri;
		}
		default: {
			throw new UnsupportedOperationException("Unknown uri: " + uri);
		}
		}
	}

	@Override
	public boolean onCreate() {
		bunniesDatabase = new BunniesDatabase(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		final SQLiteDatabase db = bunniesDatabase.getReadableDatabase();
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case COMPANIES:
			builder.setTables(Tables.COMPANIES);
			break;
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		Cursor cursor = builder.query(db, projection, selection, selectionArgs,
				null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		final SQLiteDatabase db = bunniesDatabase.getWritableDatabase();
		int updateCount = 0;
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case COMPANIES: {
			updateCount = db.update(Tables.COMPANIES, values, selection,
					selectionArgs);
			break;
		}
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		if (updateCount > 0) {
			getContext().getContentResolver().notifyChange(uri, null);
		}
		return updateCount;
	}
	
	@Override
	public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
			throws OperationApplicationException {
		final SQLiteDatabase db = bunniesDatabase.getWritableDatabase();
		db.beginTransaction();
		try {
			final int numOperations = operations.size();
			final ContentProviderResult[] results = new ContentProviderResult[numOperations];
			for (int i = 0; i < numOperations; i++) {
				results[i] = operations.get(i).apply(this, results, i);
			}
				db.setTransactionSuccessful();
				return results;
		} finally {
			db.endTransaction();
		}
	}
}
